﻿using Common;
using HslCommunication.Core;
using PLC.Domain.Dto;
using PLC.Domain.Entity;
using PLC.Domain.Enum;
using PLC.Domain.Models;
using PLC.Domain.Service.IRepository;

namespace PLC.Domain.ScheduledTasks.Strategy.Read;
/// <summary>
/// 读取状态数据
/// </summary>
public class ReadStatusData : BaseRead
{
    private readonly IPLCRepository _plcRepository;

    public ReadStatusData(IPLCRepository plcRepository)
    {
        _plcRepository = plcRepository ?? throw new ArgumentNullException(nameof(plcRepository));
    }
    public override EnumReadGroup ReadGroup { get; protected set; } = EnumReadGroup.状态数据;

    public override void Read(IReadWriteNet readWriteNet, PLCConfig plcConfig, List<DtoDataConfig> readConfigList, PLCReadModel plcReadModel)
    {
        if (readConfigList.Count == 0)
        {
            return;
        }

        foreach (var config in readConfigList)
        {
            if (config.CodeType==null)
            {
                continue;
            }
            // 读取数据
            var data = _plcRepository.ReadData(readWriteNet, config.Register, (EnumDataType)config.DataType,
                (EnumDataEncoding)(config.Encoding ?? 0), config.DataLength);
            if (config.CodeType.Value==(int)EnumStatusDataType.状态值)
            {
                var description = GetValueDescription(data, config);
                var deviceStatus = new DeviceStatus(plcConfig.DeviceConfig.DeviceId,
                    config.Register,
                    config.DataType,
                    data,
                    description);
                plcReadModel.DeviceStatus = deviceStatus;
            }else if (config.CodeType.Value==(int)EnumStatusDataType.CT值)
            {
                plcReadModel.DeviceBeat = new DeviceBeat()
                {
                    Time = data.ToInt32(),
                    DeviceName = plcConfig.DeviceConfig.DeviceName
                };
            }else if (config.CodeType.Value==(int)EnumStatusDataType.OK数量)
            {
                plcReadModel.CountModel.Add(new CountModel()
                {
                    IsOk = true,
                    Count = data.ToInt32(),
                    Name = config.Register
                });
            }else if (config.CodeType.Value==(int)EnumStatusDataType.NG数量)
            {
                plcReadModel.CountModel.Add(new CountModel()
                {
                    IsOk = false,
                    Count = data.ToInt32(),
                    Name = config.Register
                });
            }
        }
       
      
    }
    
}